<?
/*! \file
 *
 *  \brief Contiene diversas funciones para capturar la informacion 
 *  del estado de la PBX-
 *  \author Gustavo Borgoni (gborgoni@despegar.com)
 */

/*! \brief devuelve un XML con el con el estado de todos
 *  los troncales IAX2 configurados en Asterisk.
 */
function get_iax2() {
	global $asterisk;

	$xml = "\t<iax2>\n";
	if (!$iax = $asterisk->request("COMMAND", array("COMMAND" => "iax2 show peers"))) {
		$xml = "<iax>IAX ERROR</iax>";
	} else {
		$arriax = explode("\n",$iax);

		for ($i = 3; $i <= count($arriax)-5; $i++) {
			if (! is_numeric(substr($arriax[$i],0,1))) {
				// Nombre del iax
				$pos = strpos($arriax[$i]," ");
				$name = str_replace("/","",strtolower(substr($arriax[$i],0,$pos)));

				// Estado
				$pos = strpos($arriax[$i],"          ");
				$status = substr($arriax[$i],69,80);
				$xml.="\t\t<".$name.">";
				$xml.=str_replace("OK","",str_replace(")","",str_replace("(","",$status)));
				$xml.="</".$name.">\n";
			}
		}
	}
	$xml.= "\t</iax2>\n";

	return $xml;
}

/*! \brief Devuelve el total de canales y llamadas en curso */
function get_channels(){
	global $asterisk;

	if (!$channels=$asterisk->request("COMMAND", array("COMMAND" => "Show Channels"))){
		$xml = "<channels>N/A</channels>";
		$xml.= "<calls>N/A</calls>";
	} else {
		$chan = explode("\n",$channels);
		$xml = "\t<calls>".substr($chan[count($chan)-4],0,strpos($chan[count($chan)-4]," "))."</calls>\n";
		$xml.= "\t<channels>".substr($chan[count($chan)-5],0,strpos($chan[count($chan)-5], " "))."</channels>\n";
	}

	return $xml;
}

/*! \brief Devuelve la fecha y hora del sistema operativo */
function get_localtime(){
	if (!$localtime = shell_exec("date | awk {'print $4'}")) {
		$localtime = "N/A";
	} else {
		$localtime = trim($localtime,"\n");
	}

	if (!($localdate = shell_exec("date | awk {'print $1\" \"$3\" \"$2\" \"$6'}"))) {
		$localdate = "N/A";
	} else {
		$localdate = trim($localdate,"\n");
	}

	$xml = "\t<localtime>".$localtime."</localtime>\n";
	$xml.= "\t<localdate>".$localdate."</localdate>\n";

	return $xml;
}

/*! \brief Devuelve el porcentaje de disco usado */
function get_diskusage() {
	if (!($disk = shell_exec("df | awk {'print $5 '}"))) {
		$xml = "<disk>N/A</disk>";
	} else {
		$disk = explode("\n",$disk);
		$xml  = "\t<disk>".str_replace("%","",$disk[1])."</disk>\n";
	}

	return $xml;
}

/*! \brief Deveuelve el uptime del sistema operativo */
function get_pbxuptime() {
	if (!($pbxuptime = shell_exec("uptime | awk {'print $3\" \"$4\" \"$5'}" )) ){
		$xml = "\t<pbxuptime>N/A</pbxuptime>\n";
	} else {
		if (strpos($pbxuptime,"day") > 0) {
			$comma = ereg_replace("[a-zA-Z\n]","",$pbxuptime);
			$time  = explode(",",$comma);

			$day  = zero(trim($time[0], " "));
			$time = explode(":",$time[1]);

			$hour = zero(trim($time[0]," "));
			$min  = zero(trim($time[1]," "));

			if (strlen($min) < 1) {
				$min  = $hour;
				$hour = "00";	
			}

			$xml = "\t<pbxuptime>".trim($day,",")." Days ".trim($hour,",").":".trim($min,",")."</pbxuptime>\n";
		} elseif (strpos($pbxuptime,"user")>0) {
			$time = explode(":",substr($pbxuptime,0,5));

			$hour = $time[0];
			$min  = $time[1];

			if(strlen($hour)==1) $hour = "0".$hour;
			if(strlen($min) ==1) $min  = "0".$min;

			$xml = "\t<pbxuptime> 00 Days ".trim($hour,",").":".trim($min,",")."</pbxuptime>\n";

		}
	}
	return $xml;
}

/*! \brief devuelve el uptime del asterisk */
function get_astuptime(){
	global $asterisk;

	if(!$astuptime = $asterisk->request("COMMAND", array("COMMAND" => "Show Uptime"))){
		// No se consiguió el uptime del equipo
		$xml = "\t<astuptime>N/A</astuptime>\n";
	} else {
		$astuptime = strtok(strchr(strtok(strchr($astuptime,'System uptime'), "\n"),":"),":");
		$commas    = ereg_replace("[a-zA-Z]","",$astuptime);
		$cntcommas = substr_count($commas,",");

		switch($cntcommas){
			case 0: // Segundos de uptime
				$time = ereg_replace("[a-zA-Z,]","",$astuptime);
				$time = zero($time);
			
				$xml = "\t<astuptime>00 Days 00:00:".$time."</astuptime>\n";
			case 1: // Minutos
				$time = trim($commas," ");
				$min  = zero(trim(substr($time,0,2)," "));
				$seg  = zero(trim(substr($time,strpos($commas,",")+1,2)," "));

				$xml = "\t<astuptime>00 Days 00:".$min.":".$seg."</astuptime>\n";
			case 2: // Horas
				$time = explode(",",$commas);
				$hour = zero(trim($time[0]," "));
				$min  = zero(trim($time[1]," "));
				$seg  = zero(trim($time[2]," "));

				$xml = "\t<astuptime>00 Days ".$hour.":".$min.":".$seg."</astuptime>\n";
			case 3: // Dias. Semanas. Anios
				if(strpos($astuptime,"year")>0){
					$time = explode(",",$commas);

					$year = trim($time[0]," ");
					$day  = $year*365;
					$hour = zero(trim($time[1]," "));
					$min  = zero(trim($time[2]," "));
					$seg  = zero(trim($time[3]," "));

					$xml = "\t<astuptime>".$day." Days ".$hour.":".$min.":".$seg."</astuptime>\n";       
				}elseif(strpos($astuptime,"week") > 0){
					$time = explode(",",$commas);

					$week = trim($time[0]," ");
					$day  = $week*7;
					$hour = zero(trim($time[1]," "));
					$min  = zero(trim($time[2]," "));
					$seg  = zero(trim($time[3]," "));

					$xml = "\t<astuptime>".$day." Days ".$hour.":".$min.":".$seg."</astuptime>\n";
				}else{
					$time = explode(",",$commas);

					$day  = zero(trim($time[0]," "));
					$hour = zero(trim($time[1]," "));
					$min  = zero(trim($time[2]," "));
					$seg  = zero(trim($time[3]," "));

					$xml = "\t<astuptime> ".$day." Days ".$hour.":".$min.":".$seg."</astuptime>\n";
				}
			case 4: // Semana
				if(strpos($astuptime,"week") > 0 && strpos($astuptime,"day") > 0){
					$time = explode(",",$commas);

					$week = trim($time[0]," ");
					$day  = $week*7+trim($time[0]," ");

					$hour = zero(trim($time[1]," "));
					$min  = zero(trim($time[2]," "));
					$seg  = zero(trim($time[3]," "));

					$xml = "\t<astuptime> ".$day." Days ".$hour.":".$min.":".$seg."</astuptime>\n";
				}
		}
	}

	return $xml;
}

function print_err() {
	$xml = "<conf>\n";
	$xml.= "\t<aststatus>Down</aststatus>\n";
	$xml.= "\t<pbxstatus>up</pbxstatus>\n";
	$xml.= "\t<channels>0</channels>\n";
	$xml.= "\t<calls>0</calls>\n";
	$xml.= "\t<iax2>null</iax2>\n";
	$xml.= get_diskusage();
	$xml.= get_astuptime();
	$xml.= get_pbxuptime();
	$xml.= get_localtime();
	$xml.= "</conf>\n";

	return $xml;
}

/*! \brief completa una cadena con ceros 
 *  \param $str cadena de texto
 */
function zero($str){
	if (strlen($str)<1){
		return "00";
	} elseif (strlen($str) ==1) {
		return "0".$str;
	} else {
		return $str;
	}
}


?>
